<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Overseaapi_m extends CI_Model
{
    //海外仓发货
    function __construct()
    {
        parent::__construct();
    }
    //判断库存是否有货 $goodslist 商品列表  $goods_id array    $goods_number array
    public function getStocksCounts($goods_id,$storage_id,$goods_number){
        //目前使用临时海外仓库存表来判断 storage_id  0 德国 1 英国 2 美国,3万邑联（美国） $goods_id 为 goods_sku的逗号分隔
        $arr_sku = explode(",",$goods_id);
        $arr_number = explode(",",$goods_number);
        //获取库存相关信息
        $sql = "SELECT * FROM t_stocks WHERE flag = {$storage_id} ";
        $rs  = $this->db->query($sql)->result_array();
        $arr_stocks_sku = array();
        $arr_stocks_stock = array();
        foreach($rs as $key=>$value){
            $arr_stocks_sku[$key] = $value['Barcode']; //sku编码
            $arr_stocks_stock[$key]=$value['TotalInStock']; //库存数量
        }
        $isque = 1;
        foreach($arr_sku as $k=>$v){
            $ary_stocks_sku = $arr_stocks_sku;
            if(in_array($v,$arr_stocks_sku)){
                $ary_stocks_sku = array_flip($ary_stocks_sku);
                $key = $ary_stocks_sku[$v];
                //判断库存是否足够多
                //print_r($arr_number[$k]);exit;
                if($arr_stocks_stock[$key]>=$arr_number[$k]){
                }else{
                    $isque = 0;
                    break;
                }
            }else{
                $isque = 0;
                break;
            }

        }
        return $isque;
        //正式仓库 db_goods_stock 是代码需修改
        /**
        $sql = "SELECT GROUP_CONCAT(stock) as stock FROM  db_goods_stock where  goods_id in($goods_id) and storage_id = {$storage_id} ";
        $stock = $this->db->get_one($sql);
        $stocklist = explode(",",$stock["stock"]);
        $isque =1;
        foreach($stocklist as $srd)
        {
        if($srd<=0)
        {
        $isque = 0;
        break;
        }
        }
        return $isque;**/
    }
    //英华英国仓发货
    public function doSendGoodsByUkWarehouse(& $rs_order_list,& $goodslist,$deliver="YH2TK"){
        $url = "https://yinghua.co.uk/Token";
        //$username = "fuman";
        //$password = "Cosplaysky2015";
        $username = $this->config->item('ukusername');
        $password = $this->config->item('ukpass');
        //获取token
        $post_data = array ("username" => $username,"password" => $password,'grant_type'=>'password');
        $post_data = http_build_query($post_data);
        $headers = array("Content-type: Application/x-www-form-urlencoded;charset=utf-8");
        $post_arr_result = $this->sendCurlPostRequest($url,$post_data,$headers);
        $token = $post_arr_result['access_token'];
        //获取当前可用的邮递服务
        //$stocks_url = "https://yinghua.co.uk/wms/DeliveryServices";
        //$get_arr_result = $this->sendCurlGetRequest($stocks_url,$token);
        //print_r($get_arr_result);exit;
        $arr_order['OrderNumber'] = $rs_order_list['order_sn'];
        /**
        if($rs_order_list['salesOrderId']){
            $sql_express = "SELECT * FROM db_order_express WHERE name = '{$rs_order_list['shipping_name']}' ";
            $rs_express = $this->db->query($sql_express)->row_array();
            if(!empty($rs_express['oversea_express'])){
                $arr_order['DeliveryServiceCode'] = $rs_express['oversea_express']; //当为更改后的
            }else{
                $arr_order['DeliveryServiceCode'] = "YH2TK" ; //默认发货方式
            }
        }else{
            $arr_order['DeliveryServiceCode'] = "YH2TK" ; //默认发货方式
        }**/
        $arr_order['DeliveryServiceCode'] = $deliver ; //发货方式
        //收件人信息
        $arr_order['Surname'] = $rs_order_list['consignee'];//收货人
        $arr_order['FirstName'] = $rs_order_list['consignee'];
        $arr_order['Building'] = "";//非必填
        $address = "";
        if($rs_order_list['address']){
            $address .= $rs_order_list['address'] ; //当为更改后的
        }
        if($rs_order_list['address2']){
            $address .= $rs_order_list['address2'] ;
        }
        $arr_order['Street'] = $address;
        $arr_order['Area'] = $address;//非必填
        $arr_order['City'] = $rs_order_list['city'];
        $arr_order['PostCode'] = $rs_order_list['zipcode'];
        $arr_order['Country'] = $rs_order_list['country_code'];
        $arr_order['Phone'] = $rs_order_list['tel'];
        $arr_order['Mobile'] = $rs_order_list['mobile'];
        $arr_order['Email'] = $rs_order_list['paypalmail'];//非必填

        //$post_data['Items'] = ;
        foreach($goodslist as $k_g=>$k_v){
            $arr_order['Items'][$k_g]['Barcode'] = $k_v['goods_sn'];
            $arr_order['Items'][$k_g]['Quantity'] = $k_v['goods_number'];
        }
        $post_order_arr = array($arr_order);
        $order_json = json_encode($post_order_arr);
        $header = array("Authorization: Bearer {$token}","Content-type: Application/json;charset=utf-8");
        //查询货运方式显示名
        $sql_oversea = "SELECT * FROM db_order_express WHERE oversea_express = '{$deliver}' ";
        $rs_oversea  = $this->db->query($sql_oversea)->row_array();
        //正式请求  若存在则更新，否则上传新订单
        if($rs_order_list['salesOrderId']){
            $json = json_encode($arr_order);
            $stocks_url="https://yinghua.co.uk/wms/Dispatches/{$rs_order_list['salesOrderId']}";
            //返回的是状态吗
            $res_arr = $this->sendCurlCommonRequest($stocks_url,"put",$json,$header); //更新货运方式等
            if($res_arr==200||$res_arr==204){
                    //更新日志表db_goods_log
                    $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list order_id
                    $imgdata["updatetime"] = date("Y-m-d H:i:s");
                    $imgdata["createUid"] = $_COOKIE['userid'];
                    $imgdata["types"] = 3;
                    $imgdata["content"] = '英华英国仓货运方式更改成功,交易ID='.$rs_order_list['order_sn']."货运方式为:".$deliver;
                    $imgdata["createUser"] =$_COOKIE['username'];
                    $this->db->insert('db_goods_log', $imgdata);
                //1代表英国仓
                if($rs_oversea){
                    $this->db->update("db_order_list",array("shipping_name"=>$rs_oversea['name'],"shipping_id"=>$rs_oversea['id']),"order_id='".$rs_order_list["order_id"]."'");
                }
                $msg = "订单号：【".$rs_order_list['order_sn']."】英华英国仓更改货运方式成功,货运方式为{$deliver} <br/>";
                return $msg;
            }else{
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list order_id
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '英华英国仓货运方式更改失败,交易ID='.$rs_order_list['order_sn'].",货运方式为:".$deliver;
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);
                $msg = "订单号：【".$rs_order_list['order_sn']."】英华英国仓更改货运方式失败,货运方式为{$deliver} <br/>";
                return $msg;
            }

        }else{
            $stocks_url = "https://yinghua.co.uk/wms/Dispatches";
            $res_arr = $this->sendCurlPostRequest($stocks_url,$order_json,$header);
        }
        //返回值判断
        if(!empty($res_arr[0])){
            //返回值判断
            $sql_oversea = "SELECT * FROM db_order_oversea WHERE order_id = ".$rs_order_list['order_id'];
            $rs_oversea_sea  = $this->db->query($sql_oversea)->row_array();
            if($res_arr[0]['Status']==200||$res_arr[0]['Status']==204){
                //UserID 客户订单号 客户提供的订单号
                $salesOrderId = $res_arr[0]['SystemID']; //订单对应的发货单号 用于查询是否发货等信息
                if(!empty($rs_oversea_sea)){
                    $this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"isSuccess"=>1),"order_id='".$rs_order_list["order_id"]."'");
                }else{
                    $arr_oversea['order_id'] = $rs_order_list['order_id'];
                    $arr_oversea['order_sn'] = $rs_order_list['order_sn'];
                    $arr_oversea['salesOrderId'] = $salesOrderId;
                    $arr_oversea['isSuccess'] = 1;
                    $arr_oversea['addTime'] = date("Y-m-d H:i:s");
                    $this->db->insert('db_order_oversea',$arr_oversea);
                }
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list order_id
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '英华英国仓发货成功,交易ID='.$rs_order_list['order_sn']."货运方式为:".$deliver;
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);
                //1代表英国仓
                //$this->db->update("db_order_list",array("shipping_status"=>1,"shipping_number"=>$salesOrderId,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$rs_oversea['name'],"shipping_id"=>$rs_oversea['id']),"order_id='".$rs_order_list["order_id"]."'");
                $this->db->update("db_order_list",array("shipping_status"=>1,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$rs_oversea['name'],"shipping_id"=>$rs_oversea['id']),"order_id='".$rs_order_list["order_id"]."'");
                $msg = "订单号：【".$rs_order_list['order_sn']."】英华英国仓提交订单成功,货运方式为{$deliver} <br/>";
                return $msg;
            }else{
                $salesOrderId = $res_arr[0]['SystemID']; //订单对应的发货单号 用于查询是否发货等信息
                $errorMessage = $res_arr[0]['Message']; //错误信息
                if(!empty($rs_oversea_sea)){
                    $this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"errorMessage"=>$errorMessage),"order_id='".$rs_order_list["order_id"]."'");
                }else{
                    $arr_oversea['order_id'] = $rs_order_list['order_id'];
                    $arr_oversea['order_sn'] = $rs_order_list['order_sn'];
                    $arr_oversea['salesOrderId'] = $salesOrderId;
                    $arr_oversea['errorMessage'] = $errorMessage;
                    //$arr_oversea['isSuccess'] = 0; //默认值为0
                    $arr_oversea['addTime'] = date("Y-m-d H:i:s");
                    $this->db->insert('db_order_oversea',$arr_oversea);
                }
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list order_id
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '英华英国仓标配货失败,交易ID='.$rs_order_list['order_sn']."货运方式为:".$deliver;
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);

                $msg = "订单号：【".$rs_order_list['order_sn']."】英华英国仓提交订单失败,货运方式为{$deliver}".",".$errorMessage.$res_arr[0]['Status'];
                return $msg;
            }
        }else{
            $msg = "订单号：【".$rs_order_list['order_sn']."】英华英国仓提交订单失败,货运方式为{$deliver} <br/>";
            return $msg;
        }
    }
    //EZGO美国仓发货
    public function doSendGoodsByUsaWarehouse(& $rs_order_list,& $goodslist,$deliver="UPS-G-I"){
        //对接api美国仓 正式环境账号  测试环境账号 已关闭
        $customerId = $this->config->item('goodscode');
        $token = $this->config->item('usatoken');
        $usaSupplierCode = $this->config->item('usasuppliercode');
        $url = "http://openapi.4pis.com:8080/api/service/wmc/order/addSmSalerOrder?token=$token&customerId=$customerId&language=zh_CN&format=json";
        $headers= array("Content-type: Application/json;charset=utf-8");
        $arr_order['custVoucherId'] = $rs_order_list['order_sn']; //客户单证号 必填
        $arr_order['salesModel'] = 1;//销售模式 必填
        $arr_order['customerCorpId'] = "Cosplaysky"; //暂时用这个店铺测试   //店铺编号 必填 $rs_order_list['shopname']
        //$arr_order['receiver'] = $rs_order_list['consignee'];//收货人
        //$arr_order['receiverContact'] = $rs_order_list['consignee'];//receiverContact
        $arr_order['receiver'] = str_replace("\\","",$rs_order_list['consignee']);//收货人
        $arr_order['receiver'] = str_replace("'"," ",$arr_order['receiver']);//收货人
        $arr_order['receiverContact'] = str_replace("\\","",$rs_order_list['consignee']);//receiverContact
        $arr_order['receiverContact'] = str_replace("'"," ",$arr_order['receiverContact']);//receiverContact
        if(!empty($rs_order_list['tel'])){
            $phone = $rs_order_list['tel'];
        }else{
            $phone = $rs_order_list['mobile'];
        }
        if($phone){
            $arr_order['receiverContactTel'] = $phone;//联系人电话
        }else{
            $arr_order['receiverContactTel'] = "1111111111";//联系人电话 十位默认
        }
        //$arr_order['receiverContactTel'] = $phone;//联系人电话
        $arr_order['receiverPostcode'] = $rs_order_list['zipcode'];//收货人邮编
        $arr_order['receiverAddress'] = $rs_order_list['address'];//收货地址
        $address = "";
        if($rs_order_list['address']){
            $address .= $rs_order_list['address'];
        }
        if(!empty($rs_order_list['address2'])){
            $address .= $rs_order_list['address2'];
        }
        $arr_order['receiverStreet'] = $address;//收货详细地址
        $arr_order['receiverCountry'] = $rs_order_list['country_code'];//收货人国家二字码(默认中国)
        $arr_order['receiverProvince'] = $rs_order_list['province'];// 收货人省份
        $arr_order['receiverCity'] = $rs_order_list['city'];//收货人城市
        $arr_order['receiverArea'] = "";//收货人区 非必填
        $arr_order['transpostSum'] = 0;//运费 默认填写0
        foreach($goodslist as $k_goods=>$v_goods){
            $arr_order['items'][$k_goods]['productId'] = $v_goods['goods_sn'];//货品编号
            //$arr_order['items'][$k_goods]['productId'] = "16049-M";//测试 返回值salesOrderId = SOAFMWL17071700010
            $arr_order['items'][$k_goods]['planQty'] = $v_goods['goods_number'];//销售数量
            $arr_order['items'][$k_goods]['unitPrice'] = $v_goods['goods_price'];//销售单价
            $arr_order['items'][$k_goods]['stockStatus'] = "";//实物类别，默认合格品 非必填
            $arr_order['items'][$k_goods]['serialSign'] = "001";//商品记录项次(格式00X)
        }
        $arr_order['businessMemo'] = $rs_order_list['remark'];//订单备注
        $arr_order['receiveOrderTime'] = $rs_order_list['ordertime'];//销售时间
        $arr_order['warehouseId'] = $usaSupplierCode;//仓库编号 非必填
        $arr_order['warehouseName'] = "";//仓库名称 非必填
        $arr_order['orderSource'] = 16;//订单来源(API来源统一为16)
        $arr_order['paymentMethod'] = "";//非必填 支付方式（不填就默认04）
        /**
        if($rs_order_list['salesOrderId']){
            $sql_express = "SELECT * FROM db_order_express WHERE name = '{$rs_order_list['shipping_name']}' ";
            $rs_express = $this->db->query($sql_express)->row_array();
            if(!empty($rs_express['oversea_express'])){
                $arr_order['channelId'] = $rs_express['oversea_express'] ; //当为更改后的
            }else{
                $arr_order['channelId'] = "UPS-G-I" ; //默认发货方式
            }
        }else{
            $arr_order['channelId'] = "UPS-G-I" ; //默认发货方式
        }**/
        //$arr_order['channelId'] = $deliver ; //发货方式
        $arr_order['channelId'] = "";//非必填 渠道ID 如传值请用大写字母）  api要求暂时不填写
        $arr_order['transportNo'] = "";//非必填 运单号
        $arr_order['shortAddress'] = "";//非必填 大头笔
        $arr_order['originCode'] = "";//非必填 原寄地
        $arr_order['destCode'] = "";//非必填 目的地
        $arr_order['distributAddress'] = "";//集包地 非必填
        $arr_order['paymentSum'] = $rs_order_list['goods_amount'];//卖家应付金额 非必填
        $arr_order['transportNo'] = "";//运单号 非必填
        $post_data = json_encode($arr_order);
        //print_r($arr_order);exit;
        //echo $post_data;exit;
        //echo $url;exit;
        //查询货运方式显示名
        $sql_oversea = "SELECT * FROM db_order_express WHERE oversea_express = '{$deliver}' ";
        $rs_oversea  = $this->db->query($sql_oversea)->row_array();
        //发送请求
        $post_arr_result = $this->sendCurlPostRequest($url,$post_data,$headers); //返回数组值

        if(!empty($post_arr_result)){
            //返回值判断
            $sql_oversea = "SELECT * FROM db_order_oversea WHERE order_id = ".$rs_order_list['order_id'];
            $rs_oversea_sea  = $this->db->query($sql_oversea)->row_array();
            if($post_arr_result['errorCode']==0){
                $salesOrderId = $post_arr_result['data']['salesOrderId'];
                if(!empty($rs_oversea_sea)){
                    $this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"isSuccess"=>1),"order_id='".$rs_order_list["order_id"]."'");
                }else{
                    $arr_oversea['order_id'] = $rs_order_list['order_id'];
                    $arr_oversea['order_sn'] = $rs_order_list['order_sn'];
                    $arr_oversea['salesOrderId'] = $salesOrderId;
                    $arr_oversea['isSuccess'] = 1;
                    $arr_oversea['addTime'] = date("Y-m-d H:i:s");
                    $this->db->insert('db_order_oversea',$arr_oversea);
                }
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = 'EZGO美国仓标配货成功,交易ID='.$rs_order_list['order_sn'];
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);

                //3代表美国仓
                $this->db->update("db_order_list",array("shipping_status"=>3,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$rs_oversea['name'],"shipping_number"=>null,"shipping_id"=>$rs_oversea['id']),"order_id='".$rs_order_list["order_id"]."'");

                $msg = "订单号：【".$rs_order_list['order_sn']."】EZGO美国仓标配货成功,货运方式为{$deliver} <br/>";
                return $msg;
            }else{
                $salesOrderId = $post_arr_result['data']['salesOrderId'];
                $errorMessage = $post_arr_result['errorMsg']; //错误信息
                if(!empty($rs_oversea_sea)){
                    $this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"errorMessage"=>$errorMessage),"order_id='".$rs_order_list["order_id"]."'");
                }else{
                    $arr_oversea['order_id'] = $rs_order_list['order_id'];
                    $arr_oversea['order_sn'] = $rs_order_list['order_sn'];
                    $arr_oversea['salesOrderId'] = $salesOrderId;
                    $arr_oversea['errorMessage'] = $errorMessage;
                    //$arr_oversea['isSuccess'] = 0; //默认值为0
                    $arr_oversea['addTime'] = date("Y-m-d H:i:s");
                    $this->db->insert('db_order_oversea',$arr_oversea);
                }
                $msg = "订单号：【".$rs_order_list['order_sn']."】EZGO美国仓提交订单失败,货运方式为{$deliver}".",".$errorMessage;
                return $msg;
            }

        }else{
            $msg = "未知错误，无任何返回值";
            return $msg;
        }
    }
    //英华德国仓发货
    public function doSendGoodsByDeWarehouse(& $rs_order_list,& $goodslist,$deliver="DHLPEU"){
        /**
        $order_id_id = 9923;
        //通用订单数据
        $sql_order_list = "SELECT * FROM `db_order_list` WHERE order_id = '".$order_id_id."'";
        $rs_order_list = $this->db->query($sql_order_list)->row_array();
        //商品信息
        $sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods_stock b ON a.goods_id = b.goods_id WHERE a.order_id = '".$order_id_id."'";
        $goodslist = $this->db->query($sql_order_sell)->result_array();
         **/

        //测试德国仓
        $url = "https://yinghuaglobal.de/Token";
        $username = $this->config->item('germanyusername');
        $password = $this->config->item('germanypass');
        //获取token
        $post_data = array ("username" => $username,"password" => $password,'grant_type'=>'password');
        $post_data = http_build_query($post_data);
        $headers = array("Content-type: Application/x-www-form-urlencoded;charset=utf-8");
        $post_arr_result = $this->sendCurlPostRequest($url,$post_data,$headers);
        //result['access_token']
        $token = $post_arr_result['access_token'];
        //$token="sjsX1gy29wh9wsJIlDGNJtHMj8n5eRNGAtT6k8iLcLLB3BAL7OgTDbOQk4FWlRdFnZ5KN-yyYUisxkhD5eTL5U2-Whyq8wNSaShho7miGRwX4tE1X20zfGtI-eNW28F6aEt8IrG9QvM5TqoxGLrm8lKCU7hKxDgMtgJJXvbVsBq_k8eklJaq5nuqaWf3CtGF9wplBM5JEd3-0lbmyuqXyxJQy1df-OcVSlcdPuOs2URp6eOa_3uTWspfnqzFaiU4xyu9qi6QFbl_jcW_wfsYcQnEEzkt_IGUGRgJzKNdd0Cxid8m6ZY-7ekPD7Y2urTAp4tujzpJbmCNZNeyfM85ObsLl8O12LUDwPw3zbXpXziGtO6Jdi8lJI2VOEiTCD_tVdIM8H31Q4wMgk06b2FrmmOzGKazmDsqqjpvFT-c3Qpc1gZPh7-VY1g64x3qX5qRANHItPstYeQQFIfNy09lmL4hL4CwXhArLxKYNnsJhrTadXYg3M-EUe_z72BFP98umGkc0GIwKU68gH2CmqTq4jTpg3";
        //echo $token;exit;
        //正式请求 上传新订单
        //$stocks_url = "https://yinghua.co.de/wms/Dispatches";
        //获取当前可用的邮递服务
        //$stocks_url = "https://yinghua.co.uk/wms/DeliveryServices";
        //$get_arr_result = $this->sendCurlGetRequest($stocks_url,$token);
        //print_r($get_arr_result);exit;
        $arr_order['OrderNumber'] = $rs_order_list['order_sn'];
        //收件人信息
        $arr_order['Surname'] = addslashes($rs_order_list['consignee']);//收货人
        $arr_order['FirstName'] = addslashes($rs_order_list['consignee']);
        $arr_order['Building'] = "";//非必填
        $address="";
        if($rs_order_list['address']){
            $address .= $rs_order_list['address'] ; //当为更改后的
        }
        if($rs_order_list['address2']){
            $address .= $rs_order_list['address2'] ;
        }
        $arr_order['Street'] = addslashes($address);
        $arr_order['Area'] = "";//非必填
        $arr_order['City'] = $rs_order_list['city'];
        $arr_order['PostCode'] = $rs_order_list['zipcode'];
        $arr_order['Country'] = $rs_order_list['country_code'];
        $arr_order['Phone'] = $rs_order_list['tel'];
        $arr_order['Mobile'] = $rs_order_list['mobile'];
        $arr_order['Email'] = $rs_order_list['paypalmail'];//非必填
        /**
        if($rs_order_list['salesOrderId']){
            $sql_express = "SELECT * FROM db_order_express WHERE name = '{$rs_order_list['shipping_name']}' ";
            $rs_express = $this->db->query($sql_express)->row_array();
            if($rs_express['oversea_express']){
                $arr_order['DeliveryServiceCode'] = $rs_express['oversea_express'] ; //当为更改后的
            }else{
                $arr_order['DeliveryServiceCode'] = "DHLPEU" ; //默认发货方式
            }

        }else{
            $arr_order['DeliveryServiceCode'] = "DHLPEU" ; //默认发货方式 DHLPEU
        }**/
        $arr_order['DeliveryServiceCode'] = $deliver ; //发货方式
        //$post_data['Items'] = ;
        foreach($goodslist as $k_g=>$k_v){
            $arr_order['Items'][$k_g]['Barcode'] = $k_v['goods_sn'];
            $arr_order['Items'][$k_g]['Quantity'] = $k_v['goods_number'];
        }
        $post_order_arr = array($arr_order);
        $order_json = json_encode($post_order_arr);
        //echo json_encode($arr_order);exit;

        $header = array("Authorization: Bearer {$token}","Content-type: Application/json;charset=utf-8");
        //查询货运方式显示名
        $sql_oversea = "SELECT * FROM db_order_express WHERE oversea_express = '{$deliver}' ";
        $rs_oversea  = $this->db->query($sql_oversea)->row_array();
        //正式请求  若存在则更新，否则上传新订单
        if($rs_order_list['salesOrderId']){
            $json = json_encode($arr_order);
            $stocks_url="https://yinghuaglobal.de/wms/Dispatches/{$rs_order_list['salesOrderId']}";
            $res_arr = $this->sendCurlCommonRequest($stocks_url,"put",$json,$header);
            if($res_arr==200||$res_arr==204||$res_arr==409){
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list order_id
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '英华德国仓货运方式更改成功,交易ID='.$rs_order_list['order_sn'].",货运方式为:".$deliver;
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);
                //1代表英国仓
                if($rs_oversea){
                    $this->db->update("db_order_list",array("shipping_name"=>$rs_oversea['name'],"shipping_id"=>$rs_oversea['id']),"order_id='".$rs_order_list["order_id"]."'");
                }
                $msg = "订单号：【".$rs_order_list['order_sn']."】英华德国仓更改货运方式成功,货运方式为{$deliver} <br/>";
                return $msg;
            }else{
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list order_id
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '英华德国仓货运方式更改失败,交易ID='.$rs_order_list['order_sn']."货运方式为:".$deliver.",".$res_arr;
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);
                $msg = "订单号：【".$rs_order_list['order_sn']."】英华德国仓更改货运方式失败,货运方式为{$deliver} <br/>";
                return $msg;
            }

        }else{
            $stocks_url = "https://yinghuaglobal.de/wms/Dispatches";
            $res_arr = $this->sendCurlPostRequest($stocks_url,$order_json,$header);
        }
        //返回值判断
        if(!empty($res_arr[0])){
            //返回值判断
            $sql_oversea = "SELECT * FROM db_order_oversea WHERE order_id = ".$rs_order_list['order_id'];
            $rs_oversea_sea  = $this->db->query($sql_oversea)->row_array();
            if($res_arr[0]['Status']==200||$res_arr[0]['Status']==204||$res_arr[0]['Status']==409){
                //UserID 客户订单号 客户提供的订单号
                $salesOrderId = $res_arr[0]['SystemID']; //订单对应的发货单号 用于查询是否发货等信息
                if(!empty($rs_oversea_sea)){
                    $this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"isSuccess"=>1),"order_id='".$rs_order_list["order_id"]."'");
                }else{
                    $arr_oversea['order_id'] = $rs_order_list['order_id'];
                    $arr_oversea['order_sn'] = $rs_order_list['order_sn'];
                    $arr_oversea['salesOrderId'] = $salesOrderId;
                    $arr_oversea['isSuccess'] = 1;
                    $arr_oversea['addTime'] = date("Y-m-d H:i:s");
                    $this->db->insert('db_order_oversea',$arr_oversea);
                }
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list order_id
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '英华德国仓标配货成功,交易ID='.$rs_order_list['order_sn']."货运方式为:".$deliver;
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);
                //2代表德国仓
                //$this->db->update("db_order_list",array("shipping_status"=>2,"shipping_number"=>$salesOrderId,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$rs_oversea['name'],"shipping_id"=>$rs_oversea['id']),"order_id='".$rs_order_list["order_id"]."'");
                $this->db->update("db_order_list",array("shipping_status"=>2,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$rs_oversea['name'],"shipping_id"=>$rs_oversea['id'],"shipping_number"=>null),"order_id='".$rs_order_list["order_id"]."'");
                $msg = "订单号：【".$rs_order_list['order_sn']."】英华德国仓订单提交成功,货运方式为{$deliver} <br/>";
                return $msg;
            }else{
                $salesOrderId = $res_arr[0]['SystemID']; //订单对应的发货单号 用于查询是否发货等信息
                $errorMessage = $res_arr[0]['Message']; //错误信息
                if(!empty($rs_oversea_sea)){
                    $this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"errorMessage"=>$errorMessage),"order_id='".$rs_order_list["order_id"]."'");
                }else{
                    $arr_oversea['order_id'] = $rs_order_list['order_id'];
                    $arr_oversea['order_sn'] = $rs_order_list['order_sn'];
                    $arr_oversea['salesOrderId'] = $salesOrderId;
                    $arr_oversea['errorMessage'] = $errorMessage;
                    //$arr_oversea['isSuccess'] = 0; //默认值为0
                    $arr_oversea['addTime'] = date("Y-m-d H:i:s");
                    $this->db->insert('db_order_oversea',$arr_oversea);
                }
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list order_id
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '英华德国仓标配货成功,交易ID='.$rs_order_list['order_sn']."货运方式为:".$deliver.",".$errorMessage.$res_arr[0]['Status'];
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);

                $this->db->update("db_order_list",array("shipping_status"=>2,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$rs_oversea['name'],"shipping_id"=>$rs_oversea['id'],"shipping_number"=>null),"order_id='".$rs_order_list["order_id"]."'");
                $msg = "订单号：【".$rs_order_list['order_sn']."】英华德国仓订单提交失败,货运方式为{$deliver}".",".$errorMessage.$res_arr[0]['Status'];
                return $msg;
            }
        }else{
            $msg = "订单号：【".$rs_order_list['order_sn']."】英华德国仓订单提交失败,货运方式为{$deliver} <br/>";
            return $msg;
        }
    }
    //万邑通美西仓发货
    public function doSendGoodsByWinitWarehouse(& $rs_order_list,& $goodslist,$deliver="1000111"){
        //万邑通 测试账号
        /**
        $url = "http://erp.sandbox.winit.com.cn/ADInterface/api";
        $username = "rebecca";
        $password = "888";
        $token = "89435277FA3BA272DE795559998E-";
         * */
        $date = date("Y-m-d H:i:s");
        //1.万邑通美西仓  正式环境账号
        $url = "http://api.winit.com.cn/ADInterface/api";
        $username = $this->config->item('winitusername');
        //$password = $this->config->item('winitpass');
        $token = $this->config->item('winittoken');
        /**这两个数组会传送过来
        //通用订单数据
        $sql_order_list = "SELECT * FROM `db_order_list` WHERE country_code ='US' ";
        $rs_order_list = $this->db->query($sql_order_list)->row_array();
        //商品信息
        $sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods_stock b ON a.goods_id = b.goods_id WHERE a.order_id = '".$rs_order_list["order_id"]."'";
        $goodslist = $this->db->query($sql_order_sell)->result_array();
         * */
        //提交相关订单数据 美西仓 按照签名顺序来组合，不然签名通不过
        $arr_order['address1'] = $rs_order_list['address'];
        $arr_order['address2'] = $rs_order_list['address2'];//非必填
        $arr_order['city'] = $rs_order_list['city'];
        //获取运单号是返回的值 [deliverywayId] => 1000111
        $arr_order['deliveryWayID'] = "1000111";
        //$arr_order['deliveryWayID'] = "2000003"; //最后一公里派送方式ID。最后一公里派送方式ID不可为空。可查询
        $arr_order['eBayOrderID '] = $rs_order_list['order_sn']; // 非必填项
        $arr_order['emailAddress'] = $rs_order_list['paypalmail'];//非必填
        $arr_order['insuranceTypeID'] = "1000000";//最后一公里派送方式所用保险类型ID。保险类型ID不可为空。默认为1000000
        if(!empty($rs_order_list['tel'])){
            $phone = $rs_order_list['tel'];
        }else{
            $phone = $rs_order_list['mobile'];
        }
        $arr_order['phoneNum'] = $phone;
        foreach($goodslist as $k=>$v){
            $arr_order['productList'][$k]['eBayBuyerID'] = "";//非必填
            $arr_order['productList'][$k]['eBayItemID'] = "";//非必填
            $arr_order['productList'][$k]['eBaySellerID'] = "";//非必填
            $arr_order['productList'][$k]['eBayTransactionID'] = ""; //非必填
            $arr_order['productList'][$k]['productCode'] = $v['goods_sn'];
            //$arr_order['productList'][$k]['productCode'] = "auto_sku52"; //测试
            $arr_order['productList'][$k]['productNum'] = $v['goods_number'];
            $arr_order['productList'][$k]['specification'] = "";//非必填 规格（如果此产品注册时填写了该字段，那么此为必填项，否则无法准确定位您注册的产品)如果您在注册产品时没有填写该字段，则在XML中去掉‘Specification’字段。）
        }
        //收件人相关信息
        $arr_order['recipientName'] = $rs_order_list['consignee'];//收货人
        $arr_order['region'] = $rs_order_list['province'];//收件人州名称。
        $arr_order['repeatable'] = "N";//用户授权此海外仓出库单是否可重复。是否允许重复不可为空。
        $arr_order['sellerOrderNo'] = $rs_order_list['order_sn']; //卖家订单号。 非必填项
        $arr_order['state'] = $rs_order_list['country_code'];//收件人国家名称，可使用国家英文全称或是ISO国家代码。
        $arr_order['warehouseID'] = "1000008";//万邑通海外仓ID，唯一，可查询。
        $arr_order['zipCode'] = $rs_order_list['zipcode'];
        $arr_order['isShareOrder'] = "";//非必填
        //$arr_order['doorplateNumbers'] = "";//派送方式为DHL、UK DPD，门牌号必填
        //$arr_order['platform'] = "";//非必填
        $arr_order['fromBpartnerId'] = "";//非必填

        //相关签名信息
        $post_data = array();
        //1.创建海外仓出库单（草稿）createOutboundInfo 2.创建海外仓出库单（确认中）createOutboundOrder
        //当出库单处在草稿状态中时，用户可通过API作废出库单。
        $post_data['action'] ="createOutboundOrder" ;
        $post_data['app_key'] = $username;
        $post_data['data'] = $arr_order;
        $post_data['format'] = "json";
        $post_data['language'] ="zh_CN";
        $post_data['platform'] = "SELLERERP";
        $post_data['sign_method'] = "md5";
        $post_data['timestamp'] = $date;
        $post_data['version'] = "1.0";
        //上述为签名所用字段
        $con_data = $token;
        $con_data.= "action".$post_data['action'].
            "app_key".$post_data['app_key'].
            "data".json_encode($post_data['data']).
            "format".$post_data['format'].
            "platform".$post_data['platform'].
            "sign_method".$post_data['sign_method'].
            "timestamp".$post_data['timestamp'].
            "version".$post_data['version'];
        $con_data.= $token;
        $sign = strtoupper(md5($con_data));
        $post_data['sign'] = $sign;
        $json_post = json_encode($post_data);
        //echo $json_post;exit;
        $post_arr_result = $this->sendCurlPostRequest($url,$json_post,$headers=array());
        //返回值  Array ( [code] => 0 [data] => Array ( [outboundOrderNum] => WO0000002520 ) [msg] => 成功 )
        //重复提交 Array ( [code] => 2020240140 [data] => [msg] => 当前卖家订单号与订单[WO0000002520]重复 )
        //print_r($post_arr_result);exit;
        if(!empty($post_arr_result)){
            //返回值判断
            $sql_oversea = "SELECT * FROM db_order_oversea WHERE order_id = ".$rs_order_list['order_id'];
            $rs_oversea_sea  = $this->db->query($sql_oversea)->row_array();
            if($post_arr_result['code']==0){
                $salesOrderId = $post_arr_result['data']['outboundOrderNum'];
                if(!empty($rs_oversea_sea)){
                    $this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"isSuccess"=>1),"order_id='".$rs_order_list["order_id"]."'");
                }else{
                    $arr_oversea['order_id'] = $rs_order_list['order_id'];
                    $arr_oversea['order_sn'] = $rs_order_list['order_sn'];
                    $arr_oversea['salesOrderId'] = $salesOrderId;
                    $arr_oversea['isSuccess'] = 1;
                    $arr_oversea['addTime'] = date("Y-m-d H:i:s");
                    $this->db->insert('db_order_oversea',$arr_oversea);
                }
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '万邑通美西仓标发货成功,交易ID='.$rs_order_list['order_sn'];
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);

                //4代表万邑通 美西仓
                $this->db->update("db_order_list",array("shipping_status"=>4,"shipping_number"=>null,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3),"order_id='".$rs_order_list["order_id"]."'");

                $msg = "订单号：【".$rs_order_list['order_sn']."】万邑通美西仓订单提交成功,货运方式为{$deliver} <br/>";
                return $msg;
            }else{
                $salesOrderId = $post_arr_result['data']['outboundOrderNum'];
                $errorMessage = $post_arr_result['msg']; //错误信息
                if(!empty($rs_oversea_sea)){
                    $this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"errorMessage"=>$errorMessage),"order_id='".$rs_order_list["order_id"]."'");
                }else{
                    $arr_oversea['order_id'] = $rs_order_list['order_id'];
                    $arr_oversea['order_sn'] = $rs_order_list['order_sn'];
                    $arr_oversea['salesOrderId'] = $salesOrderId;
                    $arr_oversea['errorMessage'] = $errorMessage;
                    //$arr_oversea['isSuccess'] = 0; //默认值为0
                    $arr_oversea['addTime'] = date("Y-m-d H:i:s");
                    $this->db->insert('db_order_oversea',$arr_oversea);
                }
                //更新日志表db_goods_log
                $imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list order_id
                $imgdata["updatetime"] = date("Y-m-d H:i:s");
                $imgdata["createUid"] = $_COOKIE['userid'];
                $imgdata["types"] = 3;
                $imgdata["content"] = '万邑通美西仓标配货失败,交易ID='.$rs_order_list['order_sn']."货运方式为:".$deliver.",".$errorMessage;
                $imgdata["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $imgdata);

                $msg = "订单号：【".$rs_order_list['order_sn']."】万邑通美西仓订单提交失败,货运方式为{$deliver}".",".$errorMessage;
                return $msg;
            }
        }else{
            $msg = "订单号：【".$rs_order_list['order_sn']."】万邑通美西仓订单提交失败,货运方式为{$deliver} <br/>";
            return $msg;
        }
    }
    //模拟post请求
    public function sendCurlPostRequest($url,$post_data,$headers){
        $ch = curl_init($url);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
        // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        //print_r($output);exit;
        curl_close($ch);
        $output= json_decode($output,1);
        return $output;
    }
    //模拟get请求
    public function sendCurlGetRequest($url,$token){
        $headers = array("Authorization: Bearer {$token}");
        $ch = curl_init($url);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        curl_close($ch);
        $output= json_decode($output,1);
        return $output;

    }
    //模拟CURL请求
    public function sendCurlCommonRequest($url,$method="post",$post_data,$headers){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        if(count($headers)>0){
            curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        }
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $method = strtoupper($method);
        switch ($method){
            case "GET":
                //curl_setopt($ch, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                curl_setopt($ch,CURLOPT_POST,1);
                curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
            case "PUT":
                curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
                break;
            case "DELETE":
                curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                //curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
                break;
        }
        // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        //var_dump($output);exit;
        curl_close($ch);

        return $httpCode;
        //return $output;
    }



}


?>